﻿using System.Reflection;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using ZeroSum.Extend.EFCore.MySql.EntityFrameworks;

namespace Blog.EFCore.Migrations;

public class DbContextFactory : IDesignTimeDbContextFactory<ZeroSumDbContext>
{
    public ZeroSumDbContext CreateDbContext(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();

        var mode = config["Mode"];
        var connectionString = args.Length > 0 ? args[0] : config[$"ConnectionStrings:{mode}"];

        var optionsBuilder = new DbContextOptionsBuilder<ZeroSumDbContext>();
        var serverVersion = new MySqlServerVersion(ServerVersion.AutoDetect(connectionString));
        optionsBuilder.UseMySql(
            connectionString, serverVersion,
            b => b.MigrationsAssembly(Assembly.GetExecutingAssembly().GetName().Name)
        );

        return new ZeroSumDbContext(optionsBuilder.Options);
    }
}